/*
 * The MIT License
 *
 * Copyright (c) 2012 Steven G. Brown
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package hudson.plugins.timestamper.annotator;

import hudson.Extension;
import hudson.ExtensionList;
import hudson.console.ConsoleAnnotator;
import hudson.console.ConsoleAnnotatorFactory;
import hudson.model.InvisibleAction;
import hudson.model.RootAction;
import hudson.model.Run;
import hudson.plugins.timestamper.TimestampNote;
import hudson.plugins.timestamper.format.TimestampFormat;
import hudson.plugins.timestamper.format.TimestampFormatProvider;
import jenkins.YesNoMaybe;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest2;

/**
 * Provides the initial {@link TimestampAnnotator} for an annotated console output.
 *
 * @author Steven G. Brown
 */
@Extension(dynamicLoadable = YesNoMaybe.YES)
public final class TimestampAnnotatorFactory3 extends ConsoleAnnotatorFactory<Run<?, ?>> {

    /** {@inheritDoc} */
    @Override
    public ConsoleAnnotator<Run<?, ?>> newInstance(Run<?, ?> build) {
        if (TimestampNote.useTimestampNotes(build.getClass())) {
            return null; // not using this system
        }
        StaplerRequest2 request = Stapler.getCurrentRequest2();
        // JENKINS-16778: The request can be null when the slave goes off-line.
        if (request == null) {
            return null; // do not annotate
        }
        long offset = getOffset(request);
        ConsoleLogParser logParser = new ConsoleLogParser(offset);
        return new TimestampAnnotator(logParser);
    }

    /**
     * Get the current offset for viewing the console log. A non-negative offset is from the start of
     * the file, and a negative offset is back from the end of the file.
     *
     * @return the offset in bytes
     */
    private static long getOffset(StaplerRequest2 request) {
        String path = request.getPathInfo();
        if (path == null) {
            // JENKINS-16438
            path = request.getServletPath();
        }
        if (path.endsWith("/consoleFull")) {
            // Displaying the full log of a completed build.
            return 0;
        }
        if (path.endsWith("/console")) {
            // Displaying the tail of the log of a completed build.
            // This duplicates code found in /hudson/model/Run/console.jelly
            // TODO: Ask Jenkins for the console tail size instead.
            String threshold = System.getProperty("hudson.consoleTailKB", "150");
            return -(Long.parseLong(threshold) * 1024);
        }
        // Displaying the log of a build in progress.
        // The start parameter is documented on the build's remote API page.
        String startParameter = request.getParameter("start");
        return startParameter == null ? 0 : Long.parseLong(startParameter);
    }

    /**
     * Get the URL for displaying the plain text console and time-stamps in the current format.
     *
     * @return the plain text URL
     */
    public String getPlainTextUrl() {
        TimestampFormat format = TimestampFormatProvider.get();
        return format.getPlainTextUrl();
    }

    /**
     * Make {@link hudson.plugins.timestamper.annotator.TimestampAnnotatorFactory3} available via HTTP
     * in preparation of {@code /extensionList/} URL removal.
     */
    // TODO Consider reusing
    //  /hudson.console.ConsoleAnnotatorFactory/hudson.plugins.timestamper.annotator.TimestampAnnotatorFactory3/ on
    //  Jenkins 2.505, but that would require that URL to be stable API.
    @Restricted(NoExternalUse.class)
    @Extension
    public static class RootActionImpl extends InvisibleAction implements RootAction, StaplerProxy {
        @Override
        public String getUrlName() {
            return "hudson.plugins.timestamper.annotator.TimestampAnnotatorFactory3";
        }

        @Override
        public Object getTarget() {
            return ExtensionList.lookupSingleton(hudson.plugins.timestamper.annotator.TimestampAnnotatorFactory3.class);
        }
    }
}
